<template>
  <div v-if="visible" class="login-modal-overlay" @click="handleOverlayClick">
    <div class="login-modal" @click.stop>
      <div class="modal-header">
        <h2 class="modal-title">{{ isLogin ? '登录' : '注册' }}</h2>
        <button class="close-btn" @click="closeModal">
          <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
            <path d="M18 6L6 18M6 6L18 18" stroke="currentColor" stroke-width="2" stroke-linecap="round"/>
          </svg>
        </button>
      </div>
      
      <div class="modal-body">
        <form @submit.prevent="handleSubmit" class="login-form">
          <div class="form-group">
            <label for="userAccount">账号</label>
            <input
              id="userAccount"
              v-model="formData.userAccount"
              type="text"
              placeholder="请输入账号（4-16位字母数字下划线）"
              :class="{ 'error': errors.userAccount }"
              @blur="validateField('userAccount')"
            />
            <span v-if="errors.userAccount" class="error-message">{{ errors.userAccount }}</span>
          </div>
          
          <div class="form-group">
            <label for="userPassword">密码</label>
            <input
              id="userPassword"
              v-model="formData.userPassword"
              type="password"
              placeholder="请输入密码（6-20位）"
              :class="{ 'error': errors.userPassword }"
              @blur="validateField('userPassword')"
            />
            <span v-if="errors.userPassword" class="error-message">{{ errors.userPassword }}</span>
          </div>
          
          <div v-if="!isLogin" class="form-group">
            <label for="checkPassword">确认密码</label>
            <input
              id="checkPassword"
              v-model="formData.checkPassword"
              type="password"
              placeholder="请再次输入密码"
              :class="{ 'error': errors.checkPassword }"
              @blur="validateField('checkPassword')"
            />
            <span v-if="errors.checkPassword" class="error-message">{{ errors.checkPassword }}</span>
          </div>
          
          <div v-if="!isLogin" class="form-group">
            <label for="userName">昵称（可选）</label>
            <input
              id="userName"
              v-model="formData.userName"
              type="text"
              placeholder="请输入昵称（最多20位）"
              :class="{ 'error': errors.userName }"
              @blur="validateField('userName')"
            />
            <span v-if="errors.userName" class="error-message">{{ errors.userName }}</span>
          </div>
          
          <button type="submit" class="submit-btn" :disabled="loading">
            <span v-if="loading" class="loading-spinner"></span>
            {{ loading ? '处理中...' : (isLogin ? '登录' : '注册') }}
          </button>
        </form>
        
        <div class="modal-footer">
          <p class="switch-mode">
            {{ isLogin ? '还没有账号？' : '已有账号？' }}
            <button @click="toggleMode" class="link-btn">
              {{ isLogin ? '立即注册' : '立即登录' }}
            </button>
          </p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { userApi } from '../api/user'

const props = defineProps({
  visible: {
    type: Boolean,
    default: false
  },
  mode: {
    type: String,
    default: 'login' // 'login' or 'register'
  }
})

const emit = defineEmits(['close', 'success'])

const isLogin = ref(props.mode === 'login')
const loading = ref(false)

const formData = reactive({
  userAccount: '',
  userPassword: '',
  checkPassword: '',
  userName: ''
})

const errors = reactive({
  userAccount: '',
  userPassword: '',
  checkPassword: '',
  userName: ''
})

// 监听模式变化
watch(() => props.mode, (newMode) => {
  isLogin.value = newMode === 'login'
  resetForm()
})

// 监听显示状态变化
watch(() => props.visible, (visible) => {
  if (visible) {
    resetForm()
  }
})

// 表单验证规则
const validateField = (field) => {
  errors[field] = ''
  
  switch (field) {
    case 'userAccount':
      if (!formData.userAccount) {
        errors.userAccount = '账号不能为空'
      } else if (!/^[a-zA-Z0-9_]{4,16}$/.test(formData.userAccount)) {
        errors.userAccount = '账号必须是4-16位字母、数字或下划线'
      }
      break
      
    case 'userPassword':
      if (!formData.userPassword) {
        errors.userPassword = '密码不能为空'
      } else if (formData.userPassword.length < 6 || formData.userPassword.length > 20) {
        errors.userPassword = '密码长度必须在6-20位之间'
      }
      break
      
    case 'checkPassword':
      if (!isLogin.value) {
        if (!formData.checkPassword) {
          errors.checkPassword = '确认密码不能为空'
        } else if (formData.checkPassword !== formData.userPassword) {
          errors.checkPassword = '两次输入的密码不一致'
        }
      }
      break
      
    case 'userName':
      if (!isLogin.value && formData.userName && formData.userName.length > 20) {
        errors.userName = '昵称长度不能超过20位'
      }
      break
  }
}

// 验证整个表单
const validateForm = () => {
  validateField('userAccount')
  validateField('userPassword')
  if (!isLogin.value) {
    validateField('checkPassword')
    validateField('userName')
  }
  
  return !Object.values(errors).some(error => error !== '')
}

// 重置表单
const resetForm = () => {
  Object.keys(formData).forEach(key => {
    formData[key] = ''
  })
  Object.keys(errors).forEach(key => {
    errors[key] = ''
  })
}

// 切换登录/注册模式
const toggleMode = () => {
  isLogin.value = !isLogin.value
  resetForm()
}

// 关闭弹窗
const closeModal = () => {
  emit('close')
}

// 点击遮罩层关闭
const handleOverlayClick = () => {
  closeModal()
}

// 提交表单
const handleSubmit = async () => {
  if (!validateForm()) {
    return
  }
  
  loading.value = true
  
  try {
    if (isLogin.value) {
      // 登录
      const response = await userApi.login({
        userAccount: formData.userAccount,
        userPassword: formData.userPassword
      })
      
      if (response.code === 0) {
        // 保存用户信息和token
        localStorage.setItem('token', response.data.token)
        localStorage.setItem('userInfo', JSON.stringify(response.data))
        
        // 通知全局：登录完成
        window.dispatchEvent(new CustomEvent('user-login', { detail: response.data }))
        
        emit('success', { type: 'login', data: response.data })
        closeModal()
      } else {
        throw new Error(response.message || '登录失败')
      }
    } else {
      // 注册
      const response = await userApi.register({
        userAccount: formData.userAccount,
        userPassword: formData.userPassword,
        checkPassword: formData.checkPassword,
        userName: formData.userName
      })
      
      if (response.code === 0) {
        // 注册成功，自动切换到登录模式
        alert('注册成功！请登录')
        isLogin.value = true
        formData.userPassword = ''
        formData.checkPassword = ''
        formData.userName = ''
      } else {
        throw new Error(response.message || '注册失败')
      }
    }
  } catch (error) {
    console.error('操作失败:', error)
    alert(error.message || '操作失败，请重试')
  } finally {
    loading.value = false
  }
}
</script>

<style lang="scss" scoped>
.login-modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  backdrop-filter: blur(8px);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
  animation: fadeIn 0.3s ease-out;
}

.login-modal {
  background: linear-gradient(135deg, rgba(255, 255, 255, 0.1), rgba(255, 255, 255, 0.05));
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.2);
  border-radius: 16px;
  width: 90%;
  max-width: 400px;
  max-height: 90vh;
  overflow-y: auto;
  box-shadow: 0 20px 40px rgba(0, 0, 0, 0.3);
  animation: slideUp 0.3s ease-out;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 24px 24px 0;
  
  .modal-title {
    color: #fff;
    font-size: 24px;
    font-weight: 600;
    margin: 0;
    text-shadow: 0 2px 4px rgba(0, 0, 0, 0.3);
  }
  
  .close-btn {
    background: none;
    border: none;
    color: rgba(255, 255, 255, 0.7);
    cursor: pointer;
    padding: 8px;
    border-radius: 8px;
    transition: all 0.2s ease;
    
    &:hover {
      background: rgba(255, 255, 255, 0.1);
      color: #fff;
    }
  }
}

.modal-body {
  padding: 24px;
}

.login-form {
  .form-group {
    margin-bottom: 20px;
    
    label {
      display: block;
      color: rgba(255, 255, 255, 0.9);
      font-size: 14px;
      font-weight: 500;
      margin-bottom: 8px;
      text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
    }
    
    input {
      width: 100%;
      padding: 12px 16px;
      background: rgba(255, 255, 255, 0.1);
      border: 1px solid rgba(255, 255, 255, 0.2);
      border-radius: 8px;
      color: #fff;
      font-size: 14px;
      transition: all 0.2s ease;
      box-sizing: border-box;
      
      &::placeholder {
        color: rgba(255, 255, 255, 0.5);
      }
      
      &:focus {
        outline: none;
        border-color: rgba(135, 206, 250, 0.6);
        background: rgba(255, 255, 255, 0.15);
        box-shadow: 0 0 0 3px rgba(135, 206, 250, 0.2);
      }
      
      &.error {
        border-color: rgba(255, 99, 99, 0.6);
        background: rgba(255, 99, 99, 0.1);
      }
    }
    
    .error-message {
      display: block;
      color: #ff6b6b;
      font-size: 12px;
      margin-top: 4px;
      text-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);
    }
  }
  
  .submit-btn {
    width: 100%;
    padding: 14px;
    background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
    border: none;
    border-radius: 8px;
    color: #fff;
    font-size: 16px;
    font-weight: 600;
    cursor: pointer;
    transition: all 0.2s ease;
    display: flex;
    align-items: center;
    justify-content: center;
    gap: 8px;
    
    &:hover:not(:disabled) {
      transform: translateY(-2px);
      box-shadow: 0 8px 20px rgba(102, 126, 234, 0.4);
    }
    
    &:active:not(:disabled) {
      transform: translateY(0);
    }
    
    &:disabled {
      opacity: 0.7;
      cursor: not-allowed;
    }
    
    .loading-spinner {
      width: 16px;
      height: 16px;
      border: 2px solid rgba(255, 255, 255, 0.3);
      border-top: 2px solid #fff;
      border-radius: 50%;
      animation: spin 1s linear infinite;
    }
  }
}

.modal-footer {
  text-align: center;
  margin-top: 24px;
  
  .switch-mode {
    color: rgba(255, 255, 255, 0.7);
    font-size: 14px;
    margin: 0;
    
    .link-btn {
      background: none;
      border: none;
      color: #87ceeb;
      cursor: pointer;
      font-size: 14px;
      text-decoration: underline;
      margin-left: 4px;
      transition: color 0.2s ease;
      
      &:hover {
        color: #fff;
      }
    }
  }
}

@keyframes fadeIn {
  from {
    opacity: 0;
  }
  to {
    opacity: 1;
  }
}

@keyframes slideUp {
  from {
    opacity: 0;
    transform: translateY(30px) scale(0.95);
  }
  to {
    opacity: 1;
    transform: translateY(0) scale(1);
  }
}

@keyframes spin {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}

// 响应式设计
@media (max-width: 480px) {
  .login-modal {
    width: 95%;
    margin: 20px;
  }
  
  .modal-header {
    padding: 20px 20px 0;
    
    .modal-title {
      font-size: 20px;
    }
  }
  
  .modal-body {
    padding: 20px;
  }
}
</style>